#include "netrunnable.h"

#include "../journal.h"
#include "../wfnet.h"

using namespace wfnet;

NetRunnable::NetRunnable(WfNet *net, int repetitions) : QObject(),
    m_thread(new QThread(this)),
    m_net(net),
    m_repetitions(repetitions),
    m_quitRequest(false)
{

}

NetRunnable::~NetRunnable()
{

}

void NetRunnable::start()
{
    this->moveToThread(m_thread);
    m_thread->start();
}

void NetRunnable::quit()
{
    m_quitRequest = true;
}

void NetRunnable::run()
{
    m_net->restoreInitialMarking();

    for (int i = 0; i < m_repetitions; ++i)
    {
        m_net->m_journal->beginNewRun();

        while (!m_net->isLocked())
        {
            if (m_quitRequest)
            {
                break;
            }

            m_net->determineEnabledTransitions();
            m_net->fireRandomTransition();

            if (m_quitRequest)
            {
                break;
            }
        }

        if (!m_quitRequest)
        {
            m_net->m_journal->finishJournal();

            if (i < (m_repetitions - 1))
            {
                m_net->restoreInitialMarking();
            }
        }
        else
        {
            break;
        }
    }

    m_thread->quit();
}
